package com.swing_pinea.render;

import com.swing_pinea.event.KeyboardsListener;
import com.swing_pinea.shape.PineaRect;

import javax.swing.*;
import java.awt.*;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.function.Consumer;

public class GamePanel extends JPanel {

    private Queue<Consumer<Graphics>> renderQueue;

    public GamePanel() {
        setLayout(new BorderLayout());
        setOpaque(false);

        addKeyListener(new KeyboardsListener());
        addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                System.out.println("GamePanel获得焦点");
            }

            @Override
            public void focusLost(FocusEvent e) {
                System.out.println("GamePanel失去焦点");
            }
        });

        renderQueue = new ConcurrentLinkedQueue<>();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        Consumer<Graphics> consumer;
        while ((consumer = renderQueue.poll()) != null) {
            consumer.accept(g);
        }
    }


    public void clear(Color color) {
        renderQueue.offer(g -> {
            g.setColor(color);
            g.fillRect(0, 0, getWidth(), getHeight());
        });
    }

    public void fillRect(PineaRect rect, Color color) {
        renderQueue.offer(g -> {
            g.setColor(color);
            g.fillRect((int) rect.x, (int) rect.y, (int) rect.w, (int) rect.h);
        });
    }

    public void drawImage(PineaImage image, float x, float y) {
        renderQueue.offer(g -> {
            g.drawImage(image.getData(), (int) x, (int) y, null);
        });
    }

    public void render() {
        repaint();
    }
}
    